#!/usr/bin/perl

use strict;
use DBI;
use CGI;

# log_lister.pl
#  - Jamie Stevens 2010-08-08

# This script is a collection of subroutines for manipulating online logs.

my $in=CGI->new;

my %input=$in->Vars;

# the database handle
my $dbh;

my $action=$input{"action"};

if ($action eq "list"){
    # list available logs
    &start_database_connection;

    print $in->header('text/html');
    &list_all_logs;

    $dbh->disconnect;
}

exit;

sub list_all_logs {
    my $all_logs_query="SELECT log_id,project_code,creation_time,observer,instrument,".
	"password,identifier FROM log";
    my $all_logs=$dbh->prepare($all_logs_query);
    $all_logs->execute;
    while (my @logs_response=$all_logs->fetchrow){
	# get rid of the subseconds in the time
	$logs_response[2]=~s/^(.*)\..*/$1/;
	# just present whether a password exists
	if ($logs_response[5] ne ""){
	    $logs_response[5]="Yes";
	} else {
	    $logs_response[5]="No";
	}
	for (my $i=0;$i<=$#logs_response;$i++){
	    if ($i>0){
		print "|";
	    }
	    print $logs_response[$i];
	}
	print "\n";
    }
    $all_logs->finish;
}

sub start_database_connection {
    # Here we connect to the database as a user that can update the
    # entry table.

    my $dsn="dbi:Pg:dbname=online_log;host=localhost;port=5432";
    my $db_user="logadd";
    my $db_password="logadd";
    $dbh=DBI->connect($dsn,$db_user,$db_password,
		      {RaiseError => 0, AutoCommit => 1,
		       PrintError => 1});
}
